package util;

import factory.JankThreadFactory;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * @author jiangnk
 * @since 2018-12-12
 */
@Slf4j
public class JankExecutors {

    /**
     * 新建一个线程池
     *
     * @param nThreads 线程数量
     * @param poolName 线程池名称前缀
     * @return 创建好的线程池
     */
    public static ExecutorService newFixedSizeExecutorPool(int nThreads,String poolName){

        return new ThreadPoolExecutor(nThreads, nThreads, 0L,
                TimeUnit.MICROSECONDS,
                new LinkedBlockingDeque<>(1024),
                JankThreadFactory.newNamedThreadFactory(poolName),
                new ThreadPoolExecutor.DiscardOldestPolicy());
    }

    /**
     * 关闭线程池
     *
     * @param executor 线程池
     * @return 关闭成功-true，失败-false
     */
    public static boolean shutdown(ExecutorService executor){
        executor.shutdown();
        try {
            while (!executor.awaitTermination(1L, TimeUnit.SECONDS)) {
                log.info("thread pool is shutdown ing ...");
            }
        }catch (InterruptedException e){
            log.error("thread pool shutdown error :{}",e.getMessage());
            return false;
        }
        log.info("thread pool shutdown completed !");
        return true;
    }

}
